package com.ndp.fb.walle.business.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.esotericsoftware.minlog.Log;
import com.ndp.fb.constant.CommonConstants;
import com.ndp.fb.rdb.api.EventNotificationMessageRdbService;
import com.ndp.fb.rdb.api.UserRdbServices;
import com.ndp.fb.rdb.model.User;
import com.ndp.fb.rdb.model.message.EventNotificationMessage;
import com.ndp.fb.redis.api.RedisDistributedLockService;
import com.ndp.fb.walle.business.EventNotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Created by evan.wan on 2015/7/31.
 */
@Component
public class EventNotificationServiceImpl implements EventNotificationService {

    @Reference
    private EventNotificationMessageRdbService eventNotificationMessageRdbService;

    @Reference
    private UserRdbServices userRdbServices;

    @Autowired
    private RedisDistributedLockService redisDistributedLockService;

    @Override
    public void delById(Long id)
    {
        EventNotificationMessage eventNotificationMessage = eventNotificationMessageRdbService.findUnReadEventNotificationMessageById(id.toString());
        if(eventNotificationMessage !=null && eventNotificationMessage.getIsRead() == 0) {
            User user = userRdbServices.getUserByTicket(eventNotificationMessage.getReceiver());
            try {
                if (redisDistributedLockService.tryLock(CommonConstants.BADAGE_NUM_LOCK + user.getTicket(), 1, TimeUnit.MINUTES)) {
                    if (user.getBadgeNum() - 1 >= 0) {
                        user.setBadgeNum(user.getBadgeNum() - 1);
                    }
                    userRdbServices.update(user);
                }
            } catch (Exception ex) {
                Log.error(ex.getMessage(), ex);
            } finally {
                redisDistributedLockService.unLock(CommonConstants.BADAGE_NUM_LOCK + user.getTicket());
            }
        }
        eventNotificationMessageRdbService.delete(id);
    }

}
